import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { useUserStore } from '../../store/userStore';
import { Task } from '../../types/task';
import { message } from 'antd';
import { CheckCircleOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { List, Card, Button, Typography, Space, Tag } from 'antd';
import TaskCard from './TaskCard';

const { Title, Text } = Typography;

const TaskList: React.FC = () => {
  const [tasks, setTasks] = useState<Task[]>([]);
  const { updateUserPoints } = useUserStore();

  useEffect(() => {
    fetchTasks();
  }, []);

  const fetchTasks = async () => {
    // try {
    //   const response = await fetch('/api/tasks', {
    //     headers: {
    //       'Authorization': `Bearer ${localStorage.getItem('token')}`
    //     }
    //   });
    //   const data = await response.json();
    //   setTasks(data);
    // } catch (error) {
    //   console.error('获取任务失败:', error);
    // }
  };

  const handleComplete = async (taskId: string) => {
    try {
      const response = await fetch(`/api/tasks/${taskId}/complete`, {
        method: 'PATCH',
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      });
      
      if (!response.ok) {
        const error = await response.json();
        if (error.message === '任务尚未到可完成时间') {
          // 显示下次可完成时间
          const nextDate = new Date(error.nextAvailableDate);
          const formattedDate = nextDate.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit'
          });
          message.warning(`该任务需要等到 ${formattedDate} 才能再次完成`);
          return;
        }
        throw new Error(error.message);
      }

      const completedTask = await response.json();
      setTasks(tasks.map(task => 
        task.id === taskId ? completedTask : task
      ));
      
      // 更新用户积分
      if (completedTask.points) {
        updateUserPoints(completedTask.points);
      }
      
      message.success('任务完成！');
    } catch (error) {
      message.error('完成任务失败');
    }
  };

  const taskTypes = [
    { type: 'daily', title: '日常任务', description: '每天刷新的基础环保任务' },
    { type: 'weekly', title: '每周任务', description: '需要更多时间和努力的任务' },
    { type: 'challenge', title: '挑战任务', description: '具有挑战性的特殊环保任务' },
    { type: 'community', title: '社区任务', description: '与社区成员一起完成的任务' }
  ];

  return (
    <div style={{ padding: '20px', maxWidth: '800px', margin: '0 auto' }}>
      <Title level={2}>个性化挑战任务</Title>
      <List
        grid={{ gutter: 16, column: 1 }}
        dataSource={tasks}
        renderItem={task => (
          <List.Item>
            <TaskCard task={task} onComplete={handleComplete} />
          </List.Item>
        )}
      />
    </div>
  );
};

export default TaskList; 